import { defineStore } from 'pinia'
import { getItem, removeAllItem, setItem } from '@/util/storage'
import { Login_Path, Token_Key } from '@/config'
import { login } from '@/api/user'
import { setTimeStamp } from '@/util/auth'

const useUserStore = defineStore('userStore', {
  state: () => ({
    token: getItem(Token_Key) || '',
    userInfo: getItem('userInfo') || {},
  }),
  actions: {
    // 登录
    login ({ userCode, password }) {
      const params = { userCode, password }
      return new Promise((resolve, reject) => {
        login(params).then(res => {
          this.token = res.data.token
          this.userInfo = res.data.user
          // 保存登录时间 和 token
          setTimeStamp()
          setItem(Token_Key, res.data.token)
          setItem('userInfo', res.data.user)
          resolve()
        }).catch((err) => {
          reject(err)
        })
      })
    },
    // 登出
    logout () {
      this.token = ''
      this.userInfo = {}
      removeAllItem()
      uni.reLaunch({ url: Login_Path })
    },
    // 设置用户信息
    setUserInfo (userInfo) {
      this.userInfo = userInfo
      setItem('userInfo', userInfo)
    },
  },
})

export default useUserStore
